//	Problem 059: XOR decryption

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var ciphertext []int

func decode(password []int) (plaintext []int) {
	plaintext = make([]int, len(ciphertext))
	for i, v := range ciphertext {
		plaintext[i] = v ^ password[i%len(password)]
	}
	return
}

func p059() {
	fp, err := os.Open("./data/p059_cipher.txt")
	if err != nil {
		panic("p059_cipher.txt not found.")
	}
	defer fp.Close()
	var lines []string
	reader := bufio.NewReader(fp)
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				lines = append(lines, line)
				break
			}
			panic("Error in read file p059_cipher.txt.")
		}
		lines = append(lines, line)
	}

	split := strings.Split(lines[0], ",")
	for _, number := range split {
		integer, _ := strconv.Atoi(number)
		ciphertext = append(ciphertext, integer)
	}

	moreCharacters := 0
	key := make([]int, 3)

	for i := 97; i <= 122; i++ {
		for j := 97; j <= 122; j++ {
			for k := 97; k <= 122; k++ {
				try := []int{i, j, k}
				plaintext := decode(try)
				score := 0
				for _, v := range plaintext {
					if v >= 65 && v <= 122 {
						score++
					}
				}
				if score > moreCharacters {
					moreCharacters = score
					key = []int{i, j, k}
				}
			}
		}
	}

	//fmt.Printf("key:=%c\n", key)
	plaintext := decode(key)

	sum := 0
	for _, v := range plaintext {
		// fmt.Print(string(byte(v)))
		sum += v
	}

	fmt.Println("Problem 059:", sum)
}
